package xyz.keyon.dao.impl;

import xyz.keyon.bean.User;
import xyz.keyon.dao.IUserDao;
import xyz.keyon.utils.JdbcUtils;
import java.sql.*;

public class UserDaoImpl implements IUserDao {
    @Override
    public boolean addUser(String username, String password) {
        Connection conn = null;
        try {
            //连接数据库
            conn = JdbcUtils.getConnection();
            //执行sql语句
            String sql = "INSERT INTO user(username,password) VALUES(?,?)";
            Object[] params = {username, password};
            int count = JdbcUtils.executeUpdate(sql, params);
            //处理返回结果
            if(count > 0) {
                return true;
            } else {
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //释放资源
            JdbcUtils.release(null, null, conn);
        }
        return false;
    }

    @Override
    public User findUserByUsernameAndPassword(String username, String password) {
        Connection conn = null;
        ResultSet rs = null;
        try {
            //连接数据库
            conn = JdbcUtils.getConnection();
            //执行sql语句
            String sql = "SELECT * FROM user WHERE username=? AND password=?";
            Object[] params = {username, password};
            rs = JdbcUtils.executeQuery(sql,params); //调用通用的查询工具
            //处理返回结果
            while(rs.next()){
                User user = new User();
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //释放资源
            JdbcUtils.release(rs, null, conn);
        }
        return null;
    }

    @Override
    public boolean isExistUser(String username) {
        Connection conn = null;
        ResultSet rs = null;
        try {
            //连接数据库
            conn = JdbcUtils.getConnection();
            //执行sql语句
            String sql = "SELECT * FROM user WHERE username=?";
            Object[] params = {username};
            rs = JdbcUtils.executeQuery(sql,params);
            //处理返回结果
            if(rs.next()) {
                return true;
            } else {
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            JdbcUtils.release(rs,null,conn);
        }
        return false;
    }
}
